package zsh.service.impl;

import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import zsh.core.BusinessException;
import zsh.domain.User;
import zsh.mapper.UserMapper;
import zsh.service.IUserService;
import zsh.utils.MD5Utils;

@Service
@AllArgsConstructor
public class UserServiceImpl implements IUserService {
    private final UserMapper userMapper;

    //登陆
    @Override
    public User login(String username, String password) {
        User user = userMapper.getUserByUserName(username);
        if(user == null){
            throw new BusinessException(404,"您登陆的用户不存在");
        }
        if (!user.getPassword().equals(MD5Utils.md5(MD5Utils.md5(password)))){
            throw new BusinessException(500,"密码错误");
        }
        user.setPassword("");

        return user;
    }

    //注册
    @Override
    public int addUser(User user) {
        //检验账号是否存在
        User newUser = userMapper.getUserByUserName(user.getUsername());
        if(newUser != null){
            throw new BusinessException(500,"此用户名已存在");
        }
        user.setPassword(MD5Utils.md5(MD5Utils.md5(user.getPassword())));
        return userMapper.insertUser(user);
    }
}
